package com.the8thfold.anton.ant

import grails.plugin.multitenant.core.groovy.compiler.MultiTenant
import com.the8thfold.anton.users.User

@MultiTenant
class AntJobRunResults {

    static constraints = {
        dateRun(nullable: true)
        runBy(nullable: true)
        runLog(nullable: true)
        runErrorLog(nullable: true)
        notifiedUsers(nullable: true)
    }
    static transients = ['created', 'running', 'complete']
    static belongsTo = [job:AntJob]
    static hasMany = [ notifiedUsers:User ]

    String runResultsId
    String name
    String runLog
    String runErrorLog
    Date dateCreated
    Date dateRun
    User createdBy
    User runBy
    AntJobStatus status

    public boolean isCreated() { AntJobStatus.CREATED.equals(status)}
    public boolean isRunning() { AntJobStatus.RUNNING.equals(status)}
    public boolean isComplete() { AntJobStatus.COMPLETE.equals(status)}

    public static countVisibleByUser(String userId) {
        def count = 0
        User user = User.findByUserId(userId)
        def jobs = AntJobUser.findAllByUser(user).collect {it.job} as Set
        jobs.each {
            count += AntJobRunResults.countByJob(it)
        }
        return count
    }

    public static findAllVisibleByUser(String userId) {
        def results = []
        User user = User.findByUserId(userId)
        def jobs = AntJobUser.findAllByUser(user).collect {it.job} as Set
        jobs.each {
            results.addAll(AntJobRunResults.findAllByJob(it))
        }
        return results
    }

    public static findAllVisibleByUserAndJob(String userId, String jobId) {
        def results = []
        if (userId && !jobId){
            return findAllVisibleByUser(userId)
        } else {
            User user = User.findByUserId(userId)
            AntJob job = AntJob.findByJobId(jobId)
            def jobs = AntJobUser.findAllByUserAndJob(user,job).collect {it.job} as Set
            jobs.each {
                results.addAll(AntJobRunResults.findAllByJob(it))
            }
        }
        return results
    }
}

public enum AntJobStatus {
    CREATED, RUNNING, COMPLETE
}
